package com.test.test.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.test.test.dao.ProductInfoRepos;
import com.test.test.entity.ProductInfo;
import com.test.test.mapper.ProductInfoMapper;
import com.test.test.service.PayService;
import com.test.test.utils.KeyUtil;
import com.test.test.utils.RedisUtils;

@Service
public class PayServiceImpl implements PayService {

	private static final long TIMEOUT = 10 * 1000;

	@Autowired
	ProductInfoRepos productInfoRepos;

	@Autowired
	ProductInfoMapper productInfoMapper;
	@Autowired
	RedisUtils redisUtils;

	static Map<String, Integer> products; // 商品
	static Map<String, Integer> stock; // 库存
	static Map<String, String> order; // 订单

	static {
		products = new HashMap<String, Integer>();
		stock = new HashMap<String, Integer>();
		order = new HashMap<String, String>();
		products.put("123456", 100000);
		stock.put("123456", 100000);

	}

	@Override
	public String paySelect(String productId) {
		// TODO Auto-generated method stub
		return "今天销售" + products.get(productId) + " 剩余" + stock.get(productId) + " 当前销售" + order.size();
	}

	/**
	 * 1、synchronized 2、redis 分布式锁
	 */
	@Override
	public void pay(String productId) throws Exception {
		// TODO Auto-generated method stub
		// 添加redis 锁
		Long time = System.currentTimeMillis() + TIMEOUT;
		Boolean lockString = redisUtils.lockString(productId, String.valueOf(time));
		if (!lockString) {
			throw new Exception();
		}
		Integer stocka = stock.get(productId);
		if (stocka < 0) {
			throw new Exception();
		}

		order.put(KeyUtil.genUniqueKey(), productId);
		stocka--;
		try {
			Thread.sleep(100);
		} catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
		}
		stock.put(productId, stocka);
		// 解除redis 锁
		redisUtils.unlockString(productId, String.valueOf(time));
	}

	@Override
	public String killProduct(String productId) {
		// TODO Auto-generated method stub
		ProductInfo productInfo = productInfoRepos.findOne(productId);
		productInfo.setProductStock(productInfo.getProductStock() - 1);
		productInfoRepos.save(productInfo);
		order.put(KeyUtil.genUniqueKey(), productId);
		return "今天销售" + products.get(productId) + " 剩余" + stock.get(productId) + " 当前销售" + order.size();

	}

	@Override
	public String selectProduct(String productId) throws Exception {
		// TODO Auto-generated method stub
		ProductInfo productInfo = productInfoRepos.findOne("1");
		return "今天销售100000 剩余" + productInfo.getProductStock() + " 当前销售" + order.size();
	}

	@Override
	public String killProductMapper(String productId) {
		// TODO Auto-generated method stub
		int updateProductsStock = productInfoMapper.updateProductsStock(1, productId);
		order.put(KeyUtil.genUniqueKey(), productId);
		return "";
	}

}
